/*
 * Copyright 2002-2022 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.web.accept;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;

import org.springframework.http.MediaType;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.context.request.NativeWebRequest;

/**
 * 媒体类型 解析器 管理器
 *
 * ContentNegotiationManager 是 Spring Framework 中用于内容协商（Content Negotiation）管理的一个核心组件。内容协商是指根据客户端的偏好和服务器端的能力来决定响应的内容格式（如 HTML、JSON、XML 等）。通过使用 ContentNegotiationManager，开发者可以灵活地控制如何处理这些协商过程，并据此选择合适的视图解析器或消息转换器来生成响应。
 *
 * 主要功能
 * 		媒体类型解析：基于请求的 Accept 头、URL 后缀（如 .json 或 .xml）、查询参数等信息来确定客户端期望接收的内容类型。
 * 		视图解析：与视图解析器（View Resolver）集成，以便根据协商结果选择正确的视图进行渲染。
 * 		消息转换：在 RESTful 服务中，通常与消息转换器（HttpMessageConverter）结合使用，以将对象转换为适当的响应格式。
 * 		自定义策略：支持自定义内容协商策略，允许开发者根据应用的具体需求调整协商逻辑。
 * 使用场景
 * 		RESTful API 开发：当构建 RESTful Web 服务时，使用 ContentNegotiationManager 可以方便地支持多种数据格式（如 JSON、XML），并根据客户端请求自动返回相应格式的数据。
 * 		多视图应用：在一个同时提供 HTML 页面和 API 接口的应用程序中，ContentNegotiationManager 可以帮助区分请求是针对页面还是数据接口，并据此选择合适的视图或数据格式进行响应。
 *
 * 内容协商的工作流程
 * 		客户端发起请求：请求可能包含 Accept 头、URL 扩展名或特定查询参数来指定期望的内容类型。
 * 		ContentNegotiationManager 解析请求：根据配置的策略解析请求，确定客户端期望接收的内容类型。
 * 		选择合适的处理器：根据解析结果，选择合适的视图解析器或消息转换器来生成响应。
 * 		生成并发送响应：最终，服务器会生成符合要求的响应并发送给客户端。
 *
 * 关键点解释
 * 		favorPathExtension：是否考虑 URL 的路径扩展名来决定内容类型。例如，.json 表示希望获得 JSON 格式的响应。
 * 		favorParameter：是否考虑查询参数来决定内容类型。例如，format=json 表示希望获得 JSON 格式的响应。
 * 		ignoreAcceptHeader：是否忽略 HTTP 请求头中的 Accept 字段。如果设置为 true，则不会根据 Accept 头来进行内容协商。
 * 		defaultContentType：当无法通过其他方式确定内容类型时，默认使用的媒体类型。
 * 		mediaType：允许你定义自定义的媒体类型映射规则，比如将 json 映射到 application/json。
 *
 * <br>
 * Central class to determine requested {@linkplain MediaType media types}
 * for a request. This is done by delegating to a list of configured
 * {@code ContentNegotiationStrategy} instances.
 * <br> 中心类 用于确定请求的{@linkplain MediaType 媒体类型} for 请求.
 * 通过委托给一组配置的{@code ContentNegotiationStrategy}实例 获取 MediaType。
 *
 * <p>Also provides methods to look up file extensions for a media type.
 * This is done by delegating to the list of configured
 * {@code MediaTypeFileExtensionResolver} instances.
 * <br> 同时还提供了查找媒体类型对应的文件扩展名的方法。
 * 通过委托 一组配置的{@code MediaTypeFileExtensionResolver}实例 获取文件扩展名。
 *
 * @author Rossen Stoyanchev
 * @author Juergen Hoeller
 * @since 3.2
 */
public class ContentNegotiationManager implements ContentNegotiationStrategy, MediaTypeFileExtensionResolver {

	/**
	 * MediaType 类型解析策略列表
	 */
	private final List<ContentNegotiationStrategy> strategies = new ArrayList<>();

	/**
	 * MediaType 类型对应的文件扩展名解析策略列表
	 */
	private final Set<MediaTypeFileExtensionResolver> resolvers = new LinkedHashSet<>();


	/**
	 * Create an instance with the given list of
	 * {@code ContentNegotiationStrategy} strategies each of which may also be
	 * an instance of {@code MediaTypeFileExtensionResolver}.
	 * @param strategies the strategies to use
	 */
	public ContentNegotiationManager(ContentNegotiationStrategy... strategies) {
		this(Arrays.asList(strategies));
	}

	/**
	 * A collection-based alternative to
	 * {@link #ContentNegotiationManager(ContentNegotiationStrategy...)}.
	 * @param strategies the strategies to use
	 * @since 3.2.2
	 */
	public ContentNegotiationManager(Collection<ContentNegotiationStrategy> strategies) {
		Assert.notEmpty(strategies, "At least one ContentNegotiationStrategy is expected");
		this.strategies.addAll(strategies);
		for (ContentNegotiationStrategy strategy : this.strategies) {
			if (strategy instanceof MediaTypeFileExtensionResolver mediaTypeFileExtensionResolver) {
				this.resolvers.add(mediaTypeFileExtensionResolver);
			}
		}
	}

	/**
	 * Create a default instance with a {@link HeaderContentNegotiationStrategy}.
	 */
	public ContentNegotiationManager() {
		this(new HeaderContentNegotiationStrategy());
	}


	/**
	 * Return the configured content negotiation strategies.
	 * @since 3.2.16
	 */
	public List<ContentNegotiationStrategy> getStrategies() {
		return this.strategies;
	}

	/**
	 * Find a {@code ContentNegotiationStrategy} of the given type.
	 * @param strategyType the strategy type
	 * @return the first matching strategy, or {@code null} if none
	 * @since 4.3
	 */
	@SuppressWarnings("unchecked")
	@Nullable
	public <T extends ContentNegotiationStrategy> T getStrategy(Class<T> strategyType) {
		for (ContentNegotiationStrategy strategy : getStrategies()) {
			if (strategyType.isInstance(strategy)) {
				return (T) strategy;
			}
		}
		return null;
	}

	/**
	 * Register more {@code MediaTypeFileExtensionResolver} instances in addition
	 * to those detected at construction.
	 * @param resolvers the resolvers to add
	 */
	public void addFileExtensionResolvers(MediaTypeFileExtensionResolver... resolvers) {
		Collections.addAll(this.resolvers, resolvers);
	}

	@Override
	public List<MediaType> resolveMediaTypes(NativeWebRequest request) throws HttpMediaTypeNotAcceptableException {
		for (ContentNegotiationStrategy strategy : this.strategies) {
			List<MediaType> mediaTypes = strategy.resolveMediaTypes(request);
			if (mediaTypes.equals(MEDIA_TYPE_ALL_LIST)) {
				continue;
			}
			return mediaTypes;
		}
		return MEDIA_TYPE_ALL_LIST;
	}

	@Override
	public List<String> resolveFileExtensions(MediaType mediaType) {
		return doResolveExtensions(resolver -> resolver.resolveFileExtensions(mediaType));
	}

	/**
	 * {@inheritDoc}
	 * <p>At startup this method returns extensions explicitly registered with
	 * either {@link PathExtensionContentNegotiationStrategy} or
	 * {@link ParameterContentNegotiationStrategy}. At runtime if there is a
	 * "path extension" strategy and its
	 * {@link PathExtensionContentNegotiationStrategy#setUseRegisteredExtensionsOnly(boolean)
	 * useRegisteredExtensionsOnly} property is set to "false", the list of extensions may
	 * increase as file extensions are resolved via
	 * {@link org.springframework.http.MediaTypeFactory} and cached.
	 */
	@Override
	public List<String> getAllFileExtensions() {
		return doResolveExtensions(MediaTypeFileExtensionResolver::getAllFileExtensions);
	}

	private List<String> doResolveExtensions(Function<MediaTypeFileExtensionResolver, List<String>> extractor) {
		List<String> result = null;
		for (MediaTypeFileExtensionResolver resolver : this.resolvers) {
			List<String> extensions = extractor.apply(resolver);
			if (CollectionUtils.isEmpty(extensions)) {
				continue;
			}
			result = (result != null ? result : new ArrayList<>(4));
			for (String extension : extensions) {
				if (!result.contains(extension)) {
					result.add(extension);
				}
			}
		}
		return (result != null ? result : Collections.emptyList());
	}

	/**
	 * Return all registered lookup key to media type mappings by iterating
	 * {@link MediaTypeFileExtensionResolver}s.
	 * @since 5.2.4
	 */
	public Map<String, MediaType> getMediaTypeMappings() {
		Map<String, MediaType> result = null;
		for (MediaTypeFileExtensionResolver resolver : this.resolvers) {
			if (resolver instanceof MappingMediaTypeFileExtensionResolver mappingResolver) {
				Map<String, MediaType> map = mappingResolver.getMediaTypes();
				if (CollectionUtils.isEmpty(map)) {
					continue;
				}
				result = (result != null ? result : new HashMap<>(4));
				result.putAll(map);
			}
		}
		return (result != null ? result : Collections.emptyMap());
	}

}
